package com.hzdesk.media.koreabatchmatvector.utils;

import android.util.Log;
import android.view.MotionEvent;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * USB
 *
 * @author Mr.Lee
 */
public class UsbDeviceUtil {
    public static int getUsbNumber(MotionEvent event) {
        int deviceID = event.getDeviceId();

        String deviceNames = getDeviceName(deviceID);
        int deviceEventNum = getDeviceEventNum(deviceID, deviceNames);
        int deviceNums = getDeviceNum(deviceEventNum);
        //Log.d("lk", "deviceNames:" + deviceNames + ",deviceEventNum:" + deviceEventNum + ",deviceNums:" + deviceNums);
        return deviceNums;
        /*Map<String, String> deviceMap = getDeviceMap(deviceID);
        *//*for(Map.Entry<String, String> entry:deviceMap.entrySet()) {
            System.err.println("key= "+entry.getKey()+",value= "+entry.getValue());
			
		}*//*
		String devicePid= deviceMap.get("devicePid");
		String usbPortName =  deviceMap.get("usbPortName");
		String deviceName= deviceMap.get("deviceName");
		Log.d("lk", usbPortName);
		getDeviceNum(usbPortName);
		if(deviceName.equals(AppConfig.DESKMEDIA_LOG) && devicePid.equals(AppConfig.DESKMEDIA_PID)) {
			return getDeviceNum(usbPortName);
		}else {
			return 0;
		}*/

    }

    static String getDeviceName(int deviceID) {
        String deviceName = "";
        if (deviceID == 0)
            return deviceName;
        String lineString[] = getRoot("dumpsys input | grep Device").split("\n");
        for (int i = 0; i < lineString.length; i++) {
            if (lineString[i].contains("Device " + deviceID + ": ")) {
                deviceName = lineString[i].split("Device " + deviceID + ": ")[1].toString();
                break;
            }
        }
        return deviceName;
    }

    static int getDeviceEventNum(int deviceID, String deviceName) {
        String eventNum = "";
        String lineString[] = getRoot("dumpsys input | grep " + "\"" + deviceID + ": " + deviceName + "\" -A 2").split("\n");
        for (int i = 0; i < lineString.length; i++) {
            //Log.d("lk---getDeviceEventNum",lineString[i]);
            if (lineString[i].contains("/event")) {
                eventNum = lineString[i].split("/event")[1].toString();
                break;
            }
        }
        return Integer.parseInt(eventNum);
    }

    static int getDeviceNum(int DeviceEventNum) {
        String lineString[] = getRoot("cat /proc/bus/input/devices | grep event" + DeviceEventNum + " -B 2").split("\n");
        for (int i = 0; i < lineString.length; i++) {
            if (lineString[i].contains("S: Sysfs=")) {
                //Log.e("lk", lineString[i]);
                if (lineString[i].contains("/usb1/1-1/1-1:1.0/")) {
                    return 1;
                }
                if (lineString[i].contains("/usb1/1-1/1-1.1/")) {
                    return 1;
                }
                if (lineString[i].contains("/usb1/1-1/1-1.2/")) {
                    return 2;
                }
                if (lineString[i].contains("/usb1/1-1/1-1.3/")) {
                    return 3;
                }
                if (lineString[i].contains("/usb1/1-1/1-1.4/")) {
                    return 4;
                }
                if (lineString[i].contains("/usb6/6-1/6-1:1.0/")) {
                    return 5;
                }
                if (lineString[i].contains("/usb6/6-1/6-1.1/")) {
                    return 5;
                }
                if (lineString[i].contains("/usb6/6-1/6-1.2/")) {
                    return 6;
                }
                if (lineString[i].contains("/usb6/6-1/6-1.3/")) {
                    return 7;
                }
                if (lineString[i].contains("/usb6/6-1/6-1.4/")) {
                    return 8;
                }
                if (lineString[i].contains("/usb5/5-1/5-1:1.0/")) {
                    return 5;
                }
                if (lineString[i].contains("/usb5/5-1/5-1.1/")) {
                    return 5;
                }
                if (lineString[i].contains("/usb5/5-1/5-1.2/")) {
                    return 6;
                }
                if (lineString[i].contains("/usb5/5-1/5-1.3/")) {
                    return 7;
                }
                if (lineString[i].contains("/usb5/5-1/5-1.4/")) {
                    return 8;
                }
                if(lineString[i].contains("/usb3/3-1/3-1.1/3-1.1:1.0/")){
                    return 1;
                }
                if(lineString[i].contains("/usb3/3-1/3-1.1/3-1.1.1/3-1.1.1:1.0/")){
                    return 1;
                }
                if(lineString[i].contains("/usb3/3-1/3-1.1/3-1.1.2/3-1.1.2.2/3-1.1.2.2:1.0/")){
                    return 2;
                }
                if (lineString[i].contains("/usb3/3-1/3-1.2/3-1.2:1.0/")){
                    return 2;
                }
                if(lineString[i].contains("/usb3/3-1/3-1.1/3-1.1.2/3-1.1.2.3/3-1.1.2.3:1.0/")){
                    return 3;
                }
                if (lineString[i].contains("/usb3/3-1/3-1.3/3-1.3:1.0/")){
                    return 3;
                }
                if(lineString[i].contains("/usb3/3-1/3-1.1/3-1.1.2/3-1.1.2.4/3-1.1.2.4:1.0/")){
                    return 4;
                }
                if(lineString[i].contains("/usb3/3-1/3-1.1/3-1.1.2/3-1.1.2.1/3-1.1.2.1:1.0/")){
                    return 5;
                }
                if(lineString[i].contains("/usb3/3-1/3-1.1/3-1.1.3/3-1.1.3:1.0/")){
                    return 6;
                }
                if(lineString[i].contains("/usb3/3-1/3-1.1/3-1.1.4/3-1.1.4:1.0/")){
                    return 7;
                }

            }
        }
        return 0;
    }

    static int getDeviceNum(String usbPortName) {
        int num = 1;
        if (usbPortName.equals("5-1")) {
            num = 1;
        }
        if (usbPortName.contains("5-1.1")) {
            num = 1;
        }
        if (usbPortName.contains("5-1.2")) {
            num = 2;
        }
        if (usbPortName.contains("5-1.3")) {
            num = 3;
        }
        if (usbPortName.contains("5-1.4")) {
            num = 4;
        }
        if (usbPortName.equals("4-1")) {
            num = 5;
        }
        if (usbPortName.contains("3-1.1")) {
            num = 5;
        }
        if (usbPortName.contains("3-1.2")) {
            num = 6;
        }
        if (usbPortName.contains("3-1.3")) {
            num = 7;
        }
        if (usbPortName.contains("3-1.4")) {
            num = 8;
        }
        return num;

    }


    static Map<String, String> getDeviceMap(int deviceID) {
        Map<String, String> map = new HashMap<>();
        String deviceName = "";
        String deviceEventName = "";
        String usbPortName = "";
        String devicePid = "";
        if (deviceID == 0 || deviceID == -1)
            return map;
        String lineString[] = getRoot("dumpsys input").split("\n");
        for (int i = 0; i < lineString.length; i++) {
            if (lineString[i].contains("Device" + deviceID + ": ")) {
                deviceName = lineString[i].split(": ")[1].toString();
                deviceEventName = lineString[i].split("/dev/input/")[1].toString();
                break;
            }
        }

        lineString = getRoot("cat /proc/bus/input/devices").split("\n");
        for (int i = 0; i < lineString.length; i++) {
            //System.err.println(i+":"+lineString[i]);
            if (lineString[i].contains(",H: " + deviceEventName + ",S: ")) {
                String s[] = lineString[i].split("/usb")[1].split(":");
                String tmpString[] = s[0].split("/");
                devicePid = s[s.length - 1].split("\\.")[0];
                usbPortName = tmpString[tmpString.length - 1];
                break;
            }
        }

        map.put("deviceName", deviceName);
        map.put("deviceEventName", deviceEventName);
        map.put("usbPortName", usbPortName);
        map.put("devicePid", devicePid);

        return map;
    }


    public static String getRoot(String paramString) {
        String[] cmd = new String[]{"sh","-c",paramString};
        StringBuilder result = new StringBuilder();
        Process process = null;
        DataOutputStream os = null;
        BufferedReader bufrIn = null;
        BufferedReader bufrError = null;
        try {
            // 执行命令, 返回一个子进程对象（命令在子进程中执行）
            process = Runtime.getRuntime().exec(cmd);
            // 方法阻塞, 等待命令执行完成（成功会返回0）
            process.waitFor();

            // 获取命令执行结果, 有两个结果: 正常的输出 和 错误的输出（PS: 子进程的输出就是主进程的输入）
            bufrIn = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
            bufrError = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8"));
            // 读取输出
            String line = null;
            while ((line = bufrIn.readLine()) != null) {
                result.append(line).append('\n');
            }
            while ((line = bufrError.readLine()) != null) {
                result.append(line).append('\n');
            }
        } catch (Exception localException) {
            System.out.println("@@@@root cmd error:" + localException);
            //localException.printStackTrace();
            return "false";
        } finally {
            try {
                closeStream(bufrIn);
                closeStream(bufrError);
                closeStream(os);
                // 销毁子进程
                if (process != null) {
                    process.destroy();
                }
            } catch (Exception e) {
                System.out.println("###root cmd error:" + e);
            }
        }
        // 返回执行结果
        return result.toString();
    }

    private static void closeStream(Closeable stream) {
        if (stream != null) {
            try {
                stream.close();
            } catch (Exception e) {
                // nothing
            }
        }
    }
}
